package com.mlog.njyjy.ndop.monitor.collector.route.impl;

import cn.hutool.core.util.StrUtil;
import com.google.auto.service.AutoService;
import com.mlog.njyjy.ndop.monitor.collector.processor.ScanProcessor;
import com.mlog.njyjy.ndop.monitor.collector.route.BaseScanRoute;
import com.mlog.njyjy.ndop.monitor.collector.route.ScanRoute;
import com.mlog.njyjy.ndop.monitor.common.domain.CollectWay;
import com.mlog.njyjy.ndop.monitor.common.domain.Task;
import org.apache.camel.Exchange;
import org.apache.camel.LoggingLevel;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.processor.idempotent.FileIdempotentRepository;
import org.apache.camel.spi.IdempotentRepository;

import java.io.File;

/**
 * ftp扫描
 *
 * @author zyz
 * @version v1.0, 2020/07/29
 */
@AutoService(ScanRoute.class)
public class FtpScanRoute extends BaseScanRoute {

    private static final String FTP_TEMPLATE = "ftp://{}:{}@{}/{}?binary=true&passiveMode=true&noop=true&delay=5000&useFixedDelay=true&ftpClient.controlEncoding=UTF-8&idempotentKey=${file:name}-${file:modified}&include={}";

    public boolean support(String mode) {
        return "ftp".equalsIgnoreCase(mode);
    }

    @Override
    public RouteBuilder creatRoute(int taskId) {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                Task task = taskRepository.findOne(taskId);
                IdempotentRepository<String> ir = FileIdempotentRepository.fileIdempotentRepository(new File("log/pdt-monitor.dat"), 250, 512000);
                from(format(task))
                        .routeId("taskId-" + taskId)
                        .idempotentConsumer(header(Exchange.FILE_NAME).append("_").append(header(Exchange.FILE_LAST_MODIFIED)), ir)
                        .log(LoggingLevel.INFO, "[camel-info] ${file:path}")
                        .process(new ScanProcessor(task, taskRepository));
            }
        };
    }

    public String format(Task task) {
        CollectWay collectWay = taskRepository.findWays(task.getCollectWayId());
        return StrUtil.format(FTP_TEMPLATE, collectWay.getUsername(), collectWay.getPassword(), collectWay.getHost(), collectWay.getPath(),
                task.getProductName().concat(".").concat(task.getPdtFileExt()));
    }


}
